import 'package:casdon/app_providers.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/auto_router.dart';
import 'package:dio/dio.dart';

class ExceptionHandler {
  // bool 返回值，true 异常继续上抛，false：不再上抛
  static bool handle(dynamic e) {
    if (e is BusinessException) {
      return _handleBusinessError(e); // 业务异常处理
      // 业务错误
    } else if (e is DioException) {
      return _handleDioError(e); // 网络错误
    } else {
      return _handleUnknownError(e); // 未知错误
    }
  }

  /// 处理业务错误
  static bool _handleBusinessError(BusinessException e) {
    // 根据 code 执行不同策略（如：跳登录页、显示Toast等）
    switch (e.code) {
      case '401':
        getProvider(tuyaLoginProvider.notifier).logOut();
        getProvider(authStorageProvider.notifier).clear();
        appRouter.replaceAll([const AccountInputRoute()]);
        return false;
        break;
      default:
        return true;
    }
  }

  static bool _handleUnknownError(e) {
    return true;
  }

  static bool _handleDioError(DioException e) {
    if (e.type == DioExceptionType.connectionError ||
        e.type == DioExceptionType.connectionTimeout ||
        e.type == DioExceptionType.receiveTimeout ||
        e.type == DioExceptionType.sendTimeout) {
      const message = "网络连接断开了，请检查网络";
      ToastUtil.show(message);
      throw DioException(
        requestOptions: e.requestOptions,
        response: e.response,
        type: e.type,
        error: message,
        stackTrace: e.stackTrace,
      );
    }
    return true;
  }

  // ...其他处理逻辑...
}
